package com.sihai.core.web.struts2.interceptor;

import com.sihai.core.beans.BeanInjectionAnnotationResolver;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <code>SpringBeanInjectionInterceptor</code>用于注入标记有@Bean 的spring bean
 */
public class BeanInjectionInterceptor implements Interceptor {

    /**
     *
     */
    private static final long serialVersionUID = 7799965232934280718L;

    public void destroy() {

    }

    public void init() {
    }


    private List<Field> getFields(Class<?> target) {
        List<Field> fields = new ArrayList<Field>();
        fields.addAll(Arrays.asList(target.getDeclaredFields()));
        if (target.getSuperclass() != null && target.getSuperclass() != Object.class) {
            fields.addAll(getFields(target.getSuperclass()));
        }

        if (target.getInterfaces() != null && target.getInterfaces().length != 0) {
            for (Class<?> clazz : target.getInterfaces()) {
                fields.addAll(getFields(clazz));
            }
        }

        return fields;
    }

    public String intercept(ActionInvocation invocation) throws Exception {
        Object action = invocation.getAction();
        List<Field> fields = getFields(action.getClass());
        for (Field field : fields) {
            Object bean = BeanInjectionAnnotationResolver.resolve(field);
            if (bean != null) {
                field.setAccessible(true);
                field.set(action, bean);
            }
        }

        return invocation.invoke();
    }


}


